<?php

use yii\bootstrap\Modal;
use yii\widgets\Pjax;
use kartik\grid\GridView;
use yii\helpers\Html;
?>

<div class="input-group">
    <?php
    if ($widget->model) {
        echo $inp     = Html::activeHiddenInput($widget->model, $widget->attribute, $widget->options);
        $inputId = Html::getInputId($widget->model, $widget->attribute);
    }
    else {
        echo $inp     = Html::hiddenInput($widget->name, $widget->value, $widget->options);
        $inputId = $widget->name;
    }
    ?>
    <input type="text" id="picker_<?= $inputId ?>" class="form-control" name="tmp-username" value="<?= $user ? $user->username : '' ?>" maxlength="50">
    <span class="input-group-btn">
        <button type="button" class="btn btn-default btn-flat" data-toggle="modal" data-target="#user-list">选择</button>
    </span>
    <?php
    Modal::begin([
        'header' => '用户',
        'id'     => 'user-list'
    ]);
    
    echo Html::button('选择全部用户', ['class' => 'btn btn-info btn-flat pull-right','data-dismiss' => 'modal', 'aria-hidden'  => true, 'onclick' => 'pickUser(0, "全部用户")']);
    echo '<div class="clearfix"></div>';
    echo GridView::widget([
        'pjax'           => true,
        'condensed'      => true,
        'responsiveWrap' => false,
        'dataProvider'   => $dataProvider,
        'columns'        => [
            'username',
            [
                'header' => '',
                'format' => 'raw',
                'width'  => '100px',
                'hAlign' => 'center',
                'value'  => function ($model) {
                    return Html::button('选择', [
                                'class'        => 'btn btn-info btn-flat btn-xs',
                                'data-dismiss' => 'modal',
                                'aria-hidden'  => true,
                                'onclick'      => "pickUser({$model->id}, '{$model->username}')",
                    ]);
                }
                    ]
                ]
            ]);

            Modal::end();
            ?>
        </div>
        <script>
            var pickUser = function (id, username) {
                $('#<?= $inputId ?>').val(id);
                $('#picker_<?= $inputId ?>').val(username);
    }
</script>